package com.zhima.typehandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zhima.enums.SubTaskState;
import com.zhima.exception.subex.SubTaskStateIllegalException;
import com.zhima.typehandler.function.ListGetNullableResult;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class SubTaskStateListTypeHandler extends BaseTypeHandler<List> {
    public static List toEnum(List<String> stateStrs) {
        SubTaskState[] values = SubTaskState.values();
        return stateStrs.stream().map((s -> {
            for (SubTaskState value : values) {
                if (s.equals(value.getCode())) {
                    return value;
                }
            }
            throw new SubTaskStateIllegalException();
        })).collect(Collectors.toList());
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter, SerializerFeature.WriteEnumUsingToString));
    }

    @Override
    public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toEnum(ListGetNullableResult.listGetNullAbleResult(rs, columnName, String.class));
    }

    @Override
    public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toEnum(ListGetNullableResult.listGetNullAbleResult(rs, columnIndex, String.class));
    }

    @Override
    public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toEnum(ListGetNullableResult.listGetNullAbleResult(cs, columnIndex, String.class));
    }
}
